﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Box : MonoBehaviour
{
   //获取参数
    #region
    private Rigidbody2D rb;
    private BoxCollider2D coll;
    public Collider2D playerColl;
    public LayerMask groundlayer;

    [Header("参考参数")]
    public LayerMask player;
    public LayerMask anotherpPlayer;
    #endregion
  
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        coll = GetComponent<BoxCollider2D>();
    }

    void Update()
    {
        PhysicsCheck();
    }
    //物理检查
    public void PhysicsCheck() 
    {
        RaycastHit2D playerCheckL = Raycast(new Vector2(-0.75f, -0.49f), Vector2.left, 0.2f, player);
        RaycastHit2D anotherlayerCheckL = Raycast(new Vector2(-0.75f, -0.49f), Vector2.left, 0.2f, anotherpPlayer);
        RaycastHit2D playerCheckR = Raycast(new Vector2(0.75f, -0.49f), Vector2.right, 0.2f, player);
        RaycastHit2D anotherlayerCheckR = Raycast(new Vector2(0.75f, -0.49f), Vector2.right, 0.2f, anotherpPlayer);

        if (anotherlayerCheckR && playerCheckR)
        {
            rb.gravityScale = 1f;

        }
        else if (playerCheckL && anotherlayerCheckL)
        {
            rb.gravityScale = 1f;
        }
        else
        {
            if (coll.IsTouchingLayers(groundlayer))
            {
                rb.gravityScale = 100f;
            }
            else 
            {
                rb.gravityScale = 1f;
            }
        }
    }           

    //射线检测
    RaycastHit2D Raycast(Vector2 offset, Vector2 rayDirection, float length, LayerMask layer)
    {
        Vector2 pos = transform.position;

        RaycastHit2D hit = Physics2D.Raycast(pos + offset, rayDirection, length, layer);

        Color color = hit ? Color.green : Color.red;

        Debug.DrawRay(pos + offset, rayDirection * length, color);

        return hit;
    }
}